package com.knowledge.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AlgorithmParameters;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

;

/**
 * @author: zhaoyongke
 * @create: 2024-05-30 08:54
 * @description: 微信
 */
public class WxUtils {

    private static String xcx_appId = "wxd265b1062d132455";
    private static String xcx_secretKey = "53528cc28706b1519ea92c2a1307cea9";


    // 微信小程序 拿code 换取openid
    public static Map<String, String> getWxOpenId(String code) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        // 请求微信服务器，获取用户 oppenid

        // 微信url
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + xcx_appId
                + "&secret=" + xcx_secretKey + "&js_code=" + code + "&grant_type=authorization_code";
        //客户端
        OkHttpClient client = new OkHttpClient();
        //用url发起请求
        Request request = new Request.Builder().url(url).build();
        //拿到响应
        Response response = client.newCall(request).execute();
        //如果响应成功，打印返回值
        if (response.isSuccessful()) {
            String body = response.body().string();
            JSONObject jsonObjectResult = JSON.parseObject(body);
            Object openid = jsonObjectResult.get("openid");
            Object unionid = jsonObjectResult.get("unionid");
            System.out.println("openId:::" + openid + "unionId:" + unionid);
            map.put("sessionKey", jsonObjectResult.getString("session_key"));
            System.out.println("微信code：：：：" + code + "微信openid：" + body + "微信url：" + url);
            // 提取必要信息
            map.put("openId", jsonObjectResult.getString("openid"));
            map.put("sessionKey", jsonObjectResult.getString("session_key"));
            if (jsonObjectResult.containsKey("unionid")) {
                map.put("unionId", jsonObjectResult.getString("unionid"));
            }
            return map;
        }
        return map;
    }


//    public static String getAccessToken() throws Exception {
////        Object cacheObject_token = redisService.getCacheObject("WX_TOKEN");
////        if(cacheObject_token!=null){
////            log.info("开始获取token=======================从缓存中获取token======================:"+cacheObject_token);
////            return String.valueOf(cacheObject_token);
////        }
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
//
//        String replaceUrl = url.replace("{0}", xcx_appId_dz).replace("{1}", xcx_secretKey_dz);
//        String res = HttpUtil.get(replaceUrl);
//        JSONObject object = JSONObject.parseObject(res);
//        Object access_token = object.get("access_token");
//        String expires_in = object.get("expires_in").toString();

    /// /        redisService.setCacheObject("WX_TOKEN", access_token, Long.valueOf(expires_in), TimeUnit.SECONDS);
//        return access_token.toString();
//    }
    public static String getMiniProgramCode(String accessToken, String userId, String ercodeImage) throws Exception {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));

        // 构建请求JSON数据
        JSONObject requestData = new JSONObject();
        requestData.put("scene", "userId=" + userId);
        requestData.put("page", "pages/index/business_card/business_card");
        requestData.put("check_path", false);
        requestData.put("env_version", "trial");
//        requestData.put("env_version", "release");
        writer.write(requestData.toString());
        writer.flush();
        writer.close();
        InputStream inputStream = connection.getInputStream();

        BufferedImage bufferedImage = ImageIO.read(inputStream);
        ImageIO.write(bufferedImage, "jpg", new File(ercodeImage));
        String encode = Base64.encode(inputStream);
        inputStream.close();
        return encode;
    }

    //
    public static String getPhoneNumber(String phoneCode) throws Exception {
        //先根据appId和appSecret获取accessToken
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", xcx_appId, xcx_secretKey);
        String accessToken = String.valueOf(JSON.parseObject(HttpUtil.get(tokenUrl)).get("access_token"));
        //通过token和code来获取用户手机号
        String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken);
        // 构造正确的请求体JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("code", phoneCode);
        String body = HttpUtil.post(url, requestBody.toJSONString());
        // 解析JSON字符串s
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
        cn.hutool.json.JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getStr("phoneNumber");
        System.out.println("微信小程序获取手机号: " + phoneNumber);
        if (StringUtils.isNotEmpty(phoneNumber)) {
            return phoneNumber;
        }
        return "";
    }

    /**
     * 解密微信手机号
     *
     * @param sessionKey    会话密钥
     * @param encryptedData 加密数据
     * @param iv            初始向量
     * @return 解密后的手机号信息
     */
    public static String decryptPhoneNumber(String sessionKey, String encryptedData, String iv) {
        try {
            byte[] sessionKeyBytes = java.util.Base64.getDecoder().decode(sessionKey);
            byte[] encryptedDataBytes = java.util.Base64.getDecoder().decode(encryptedData);
            byte[] ivBytes = java.util.Base64.getDecoder().decode(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivBytes));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, parameters);

            byte[] result = cipher.doFinal(encryptedDataBytes);
            return new String(result, "UTF-8").trim();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
